<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="试卷名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试卷描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入试卷描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['answer:papers:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['answer:papers:edit']"
          >修改</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="papersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="试卷名称" align="center" prop="title" />
      <el-table-column label="试卷描述" align="center" prop="description" />
      <!-- <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['answer:papers:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['answer:papers:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body fullscreen>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="试卷描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入试卷描述" />
        </el-form-item>
        <el-button type="primary" @click="addTi" style="margin-bottom: 20px"
          >新增题目</el-button
        >
        <el-table
          border
          v-loading="loading"
          :data="form.questionsVO"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            prop="title"
          />
          <el-table-column label="题目" align="center" prop="questionText">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.questionText"
                placeholder="请输入题目"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="选项"
            align="center"
            prop="description"
            min-width="500"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                style="margin-bottom: 10px"
                @click="addChoice(scope.row.choices)"
                >添加选项</el-button
              >
              <el-table
                border
                v-loading="loading"
                :data="scope.row.choices"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="55"
                  align="center"
                />

                <el-table-column
                  label="选项（请填写A，B，C，D英文字母排序）"
                  align="center"
                  prop="id"
                >
                  <template slot-scope="scope1">
                    <el-input
                      v-model="scope1.row.optionTitle"
                      placeholder="选项"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="选项内容" align="center" prop="id">
                  <template slot-scope="scope1">
                    <el-input
                      v-model="scope1.row.optionText"
                      placeholder="选项内容"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  label="操作"
                  align="center"
                  class-name="small-padding fixed-width"
                >
                  <template slot-scope="scope1">
                    <!-- @click="deleteGg(scope.row, scope.$index)" -->
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="
                        handleDelete1(
                          scope1.row,
                          scope1.$index,
                          scope.row.choices,
                          1
                        )
                      "
                      v-hasPermi="['answer:papers:remove']"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="正确答案" align="center" prop="description">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.correctAnswer"
                placeholder="请输入正确答案"
              />
            </template>
          </el-table-column>

          <el-table-column label="分数" align="center" prop="questionText">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.score"
                :min="1"
                :max="50"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="
                  handleDelete1(scope.row, scope.$index, form.questionsVO, 2)
                "
                v-hasPermi="['answer:papers:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPapers,
  getPapers,
  delPapers,
  addPapers,
  updatePapers,
  addDetail,
  getDetail,
  del,
  delChoice,
} from "../../../api/answer/papers";

export default {
  name: "Papers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      papersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        description: null,
        startTime: null,
        endTime: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询试卷列表 */
    getList() {
      this.loading = true;
      this.queryParams.status = 1;
      listPapers(this.queryParams).then((response) => {
        this.papersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    addChoice(val) {
      val.push({
        id: null,
        isCorrect: 0,
        optionText: "",
        optionTitle: "",
        questionId: 0,
      });
    },

    addTi() {
      this.form.questionsVO.push({
        choices: [
          {
            id: null,
            isCorrect: 0,
            optionText: "",
            optionTitle: "",
            questionId: 0,
          },
        ],
        correctAnswer: "",
        id: null,
        paperId: 0,
        params: {},
        questionText: "",
        questionType: 0,
        remark: "",
        score: 0,
      });
    },
    // 表单重置
    reset() {
      this.form = {
        description: "",
        endTime: "",
        id: null,
        params: {},
        questionsVO: [],
        title: "",
      };

      console.log(this.form, "sssssssssss");
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDetail(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试卷";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form, "sadasdasdas");
      addDetail(this.form).then((res) => {
        this.open = false;
        this.getList();
      });
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      //     if (this.form.id != null) {
      //       updatePapers(this.form).then((response) => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addPapers(this.form).then((response) => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除试卷编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPapers(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    handleDelete1(val, index, arr, type) {
      if (type == 2 && val.choices.length > 0 && val.id) {
        this.$message.error("请先删除选项");
        return
      }
      if (val.id && type == 2) {
        del(val.id).then((res) => {});
      }
      if (val.id && type == 1) {
        delChoice(val.id).then((res) => {});
      }
      arr.splice(index, 1);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "answer/papers/export",
        {
          ...this.queryParams,
        },
        `papers_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
